package data

import (
	"blog/model"
	"errors"
	"time"

	"gitee.com/xchengli/blog-lib/database"

	"github.com/gin-gonic/gin"
)

type LinkDataService struct{}

// GetLinks 获取链接列表
func (s *LinkDataService) GetLinks(ctx *gin.Context, status uint) ([]model.LinkData, error) {
	var links []model.LinkData
	db := database.GetDB()

	query := db.Model(&model.LinkData{})
	if status > 0 {
		query = query.Where("is_show = ?", status)
	}

	if err := query.Order("orders ASC").Find(&links).Error; err != nil {
		return nil, err
	}

	return links, nil
}

// CreateLink 创建链接
func (s *LinkDataService) CreateLink(ctx *gin.Context, link *model.LinkData) error {
	db := database.GetDB()

	// 设置时间
	now := time.Now().Format("2006-01-02 15:04:05")
	link.AddTime = now
	link.UpdateTime = now

	// 如果没有设置排序，默认设为0
	if link.Orders == 0 {
		link.Orders = 0
	}

	return db.Create(link).Error
}

// ValidateLinkForm 验证链接表单
func (s *LinkDataService) ValidateLinkForm(ctx *gin.Context, link *model.LinkData, form map[string][]string) error {
	// 验证标题
	if link.Title == "" {
		return errors.New("标题不能为空")
	}

	// 验证链接地址
	if link.Link == "" {
		return errors.New("链接地址不能为空")
	}

	// 验证链接格式
	if !isValidURL(link.Link) {
		return errors.New("链接地址格式不正确")
	}

	return nil
}

// isValidURL 简单的URL格式验证
func isValidURL(url string) bool {
	return len(url) > 0 && (url[:7] == "http://" || url[:8] == "https://")
}
